import os
import requests
from cryptography.hazmat.primitives import serialization
from cryptography import x509
from requests.packages.urllib3.exceptions import InsecureRequestWarning

profile = os.getenv("PROFILE", "/opt/datadir")
csr_path = profile + "/csr" 
print(f"路径: {csr_path}") 

# 定义CSR文件路径
csr_file = csr_path + '/client_csr.csr'

# 1. 读取CSR文件内容（二进制模式）
with open(csr_file, 'rb') as f:  # 'rb'表示二进制读取
    csr_data = f.read()

# 2. 将二进制数据解析为CSR对象
csr = x509.load_pem_x509_csr(csr_data)

# 3. 将CSR对象转换为PEM格式字符串
csr_pem = csr.public_bytes(serialization.Encoding.PEM).decode('utf-8')

# 禁用证书验证警告（仅测试环境）
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
response = requests.post(
    'https://127.0.0.1:28290/request_cert',
    json={'csr': csr_pem, 'validity_days': 180},
    verify=False
)

if response.status_code == 200:
    certificate = response.json()['certificate']
    with open(csr_path + '/client_certificate.pem', 'w') as f:
        f.write(certificate)
    print("Certificate issued successfully!")
else:
    print("Error:", response.json()['error'])